﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using PickGold.Data.Hsts.Records;
using PickGold.Data.Hsts.General.Persist;

namespace PickGold.Data.Hsts.WaterfallTree
{
	public class TypeEngine
	{
		private static readonly ConcurrentDictionary<Type, TypeEngine> map = new ConcurrentDictionary<Type, TypeEngine>();

		public IComparer<IData> Comparer { get; set; }
		public IEqualityComparer<IData> EqualityComparer { get; set; }
		public IPersist<IData> Persist { get; set; }
		public IIndexerPersist<IData> IndexerPersist { get; set; }

		public TypeEngine()
		{
		}

		private static TypeEngine Create(Type type, bool isKeyType)
		{
			TypeEngine descriptor = new TypeEngine();

			if (isKeyType)
			{
				descriptor.Comparer = new DataComparer(type);
				descriptor.EqualityComparer = new DataEqualityComparer(type);
			}

			descriptor.Persist = new DataPersist(type);

			if (DataTypeUtils.IsAllPrimitive(type))
				descriptor.IndexerPersist = new DataIndexerPersist(type);
			else
				descriptor.IndexerPersist = null;

			return descriptor;
		}

		public static TypeEngine Default(Type type, bool isKeyType)
		{
			return map.GetOrAdd(type, Create(type, isKeyType));
		}
	}
}
